﻿using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Mvc;
using Pyramid.Models;

namespace Pyramid.Controllers
{
	public class RoleController : BaseController
	{
		public ActionResult List()
		{
			return View(Db.Roles);
		}

		public ActionResult Create()
		{
			var model = new Role();
			ViewBag.WebObjects = GetWebObjects();
			return View("Edit", model);
		}

		public ActionResult Edit(int id)
		{
			var model = Db.Roles.First(x => x.RoleId == id);
			ViewBag.WebObjects = GetWebObjects();
			return View(model);
		}

		[HttpPost]
		public ActionResult Edit(Role model, int[] selectedUserTypes)
		{
			if (selectedUserTypes != null && selectedUserTypes.Length > 0)
			{
				model.UserTypes = selectedUserTypes.Sum();
			}

			if (model.RoleId == 0)
			{
				Db.Roles.Add(model);
			}
			else
			{
				Db.Entry(model).State = EntityState.Modified;
			}
			Db.SaveChanges();
			return JSuccess("操作成功！", "tab_sys_role");
		}

		public ActionResult Delete(int id)
		{
			var model = new Role {RoleId = id};
			Db.Entry(model).State = EntityState.Deleted;
			Db.SaveChanges();
			return JSuccess("删除成功！", "tab_sys_role");
		}

		private List<WebObject> GetWebObjects()
		{
			return Db.WebObjects.ToList();
		}
	}
}